public with sharing class GenerateUtilForPlanDistribution
{
    public static String contextText {get; set;} 
    
    public Plan_Document_Inquiry__c pdi {get; set;}
    public String selectedRadio {get{ if(selectedRadio == null) selectedRadio = 'roles'; return selectedRadio;} set;}
    public List<UserRole> uRoleList {get; set;}
    
    public Map<String, User> uMap {get; set;}
    public List<User> uList {get; set;}
    public List<User> participantsList {get; set;}
    public List<BatchedUser__c> batchedUserList {get; set;}
    private List<User> participantsWithNoManagerAssigned {get; set;}
    private List<User> inactiveParticipants {get; set;}
    
    public String[] selectedVals {get; set;}
    public List<SelectOption> optionDetails {get; set;}
    public String[] selectedVals2 {get; set;}
    public List<SelectOption> optionDetails2 {get; set;}
    
    private String batchId{get; set;}
    private String sRL{get; set;}
    public String title {get; set;}
    public String uVal {get; set;}
    public String planComment {get; set;}
    
    public String selectedRadioLabel {get; set;}
    public Boolean showSelectedRadioLabel {get; set;}
    
    public List<String> showRoleTitleList {get; set;} 
    public Map<Id, BatchedUser__c> batchedUserMap = new Map<Id, BatchedUser__c>();
    public Map<Id, BatchedUser__c> batchedUserMap1 = new Map<Id, BatchedUser__c>();
    public Map<Id, BatchedUser__c> batchedUserMap2 = new Map<Id, BatchedUser__c>();
    public Map<Id, BatchedUser__c> batchedUserMap3 = new Map<Id, BatchedUser__c>();
    public Map<Id, BatchedUser__c> batchedUserMap4 = new Map<Id, BatchedUser__c>();
    
    public Map<Id, Id> usersManagerMap1 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap2 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap3 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap4 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap5 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap6 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap7 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap8 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap9 = new Map<Id, Id>();
    public Map<Id, Id> usersManagerMap10 = new Map<Id, Id>();
    
    public Sales_Contract__c[] contractsList {get; set;}
    public Sales_Contract__c[] showContractsList {get; set;}
    public Boolean isBatchGenerated {get; set;}
    public Boolean isNotBatchGenerated {get; set;}
    public Boolean showContractsListBool {get; set;}
    public Batch__c batchObject {get; set;}
    private String fieldName {get; set;}     
    private String srval = '';
    
    private String formSoql = '';
    private SObject sObj {get; set;}    
    private String[] roFields {get; set;} 
    private Set<String> allowedROFields {get; set;}
    private Id loggedInUserId = UserInfo.getUserId();
    private Map<String, Schema.SObjectField> batchedUserSObjectFieldMap = new Map<String, Schema.SObjectField>(); 
    private Map<String, Schema.SObjectField> userSObjectFieldMap = new Map<String, Schema.SObjectField>(); 
    private Map<String, Schema.SObjectField> userRoleSObjectFieldMap = new Map<String, Schema.SObjectField>();  
    private Map<String, Schema.SObjectField> reportManagerSObjectFieldMap = new Map<String, Schema.SObjectField>();  
    private DataAccessControlUtil dacu = null;
    
    public GenerateUtilForPlanDistribution()
    {
        try
        {
            optionDetails = new List<SelectOption>();
            optionDetails2 = new List<SelectOption>();
            selectedVals = new String[]{};
            selectedVals2 = new String[]{};
            showSelectedRadioLabel = showContractsListBool = false;
            Boolean flag = false;
            isBatchGenerated = false;
            isNotBatchGenerated = true;
            planComment = '';
            
            pdi = new Plan_Document_Inquiry__c();
            
            dacu = new DataAccessControlUtil();
            
            batchId = ApexPages.currentPage().getParameters().get('bcId');
            if(batchId != null)
                selectedRadio = 'participants';
            
            srval = ApexPages.currentPage().getParameters().get('srval');
            if(srval != null)
            {
                selectedRadio = srval;
            }
            else
            {
                selectedRadioLabel = 'Participants';
            }
            
            if(srval == 'roles')
            {
                uRoleList = getRoleDetails();
                selectedRadioLabel = 'Roles';
                title = 'Select Roles for Plan Document Distribution';
                optionDetails.clear();
                optionDetails2.clear();
                for(UserRole ur: uRoleList)
                {
                    if(!flag)
                    {
                        optionDetails.add(new SelectOption(ur.Id, ur.Name));
                        flag = !flag;
                    }
                    else
                    {
                        optionDetails2.add(new SelectOption(ur.Id, ur.Name));
                        flag = !flag;
                    }
                }
            }
            else if(srval == 'titles')
            {
                uList = getTitleDetails();
                selectedRadioLabel = 'Titles';
                title = 'Select Titles for Plan Document Distribution';
                optionDetails.clear();
                optionDetails2.clear();
                for(User u: uList)
                {
                    if(!flag)
                    {
                        optionDetails.add(new SelectOption(u.Title, u.Title));
                        flag = !flag;
                    }
                    else
                    {
                        optionDetails2.add(new SelectOption(u.Title, u.Title));
                        flag = !flag;
                    }
                }
                
            }
            else if(srval == 'participants')
            {
                participantsList = getParticipantDetails();
                selectedRadioLabel = 'Participants';
                title = 'Select Participants for Plan Document Distribution';
                optionDetails.clear();
                optionDetails2.clear();
                for(User u: participantsList)
                {
                    if(!flag)
                    {
                        optionDetails.add(new SelectOption(u.Id, u.Name+' - '+u.UserRole.Name));
                        flag = !flag;
                    }
                    else
                    {
                        optionDetails2.add(new SelectOption(u.Id, u.Name+' - '+u.UserRole.Name));
                        flag = !flag;
                    }
                }
                
            }
            
            if(batchId != null)
            {
                getUserManagers();
                Map<String, BatchedUser__c> afterBatchMap = new Map<String, BatchedUser__c>();
                Integer afterBatchMapCount = 0; 
                
                
                SObject sBatchedUserObj = new BatchedUser__c();
                //get sObjectField Map for BatcheddUser__c
                batchedUserSObjectFieldMap = dacu.getFieldMap(sBatchedUserObj);
                
                String[] bUserROFields = new String[]{'UserRoleId__c','User_Title__c','UserId__c'}; 
                allowedROFields = dacu.getAccessibleFields(sBatchedUserObj, batchedUserSObjectFieldMap, bUserROFields);
                
                if(!allowedROFields.isEmpty())
                {
                    formSoql = 'Select ';
                    for(String roField: allowedROFields)
                    {
                        formSoql += roField+', ';
                    }
                    formSoql = formSoql.substring(0, formSoql.length() - 2);
                    formSoql += ' from BatchedUser__c where ownerId = :loggedInUserId ';

                    bUserROFields = new String[]{'BatchId__c'}; 
                    allowedROFields = dacu.getAccessibleFields(sBatchedUserObj, batchedUserSObjectFieldMap, bUserROFields);
                    if(!allowedROFields.isEmpty())
                    {
                        for(String roField: allowedROFields)
                        {
                            formSoql += ' and '+roField+' = :batchId ';
                        }
                        for(BatchedUser__c[] bUL : Database.query(formSoql))
                        {
                            for(BatchedUser__c bu: bUL)
                            {
                                if(selectedRadio == 'roles' && afterBatchMapCount < 1000)
                                    afterBatchMap.put(bu.UserRoleId__c, bu);
                                else if(selectedRadio == 'titles' && afterBatchMapCount < 1000)
                                    afterBatchMap.put(bu.User_Title__c, bu);
                                else if(afterBatchMapCount < 1000)
                                    afterBatchMap.put(bu.UserId__c, bu);
                                    
                                afterBatchMapCount++;
                                
                                if(batchedUserMap.size() < 1000)
                                    batchedUserMap.put(bu.UserId__c, bu);
                                else if(batchedUserMap1.size() < 1000)
                                    batchedUserMap1.put(bu.UserId__c, bu);
                                else if(batchedUserMap2.size() < 1000)
                                    batchedUserMap2.put(bu.UserId__c, bu);
                                else if(batchedUserMap3.size() < 1000)
                                    batchedUserMap3.put(bu.UserId__c, bu);
                                else if(batchedUserMap4.size() < 1000)
                                    batchedUserMap4.put(bu.UserId__c, bu);
                                    
                            }
                        }
                    }
                }
                
                Set<String> afterBatchSet = afterBatchMap.keyset();
                if(selectedRadio == 'roles')
                {
                    showRoleTitleList = new List<String>();
                    sObj = new UserRole();
                    userRoleSObjectFieldMap = dacu.getFieldMap(sObj);
                    
                    roFields = new String[]{'Name'}; 
                    allowedROFields = dacu.getAccessibleFields(sObj, userRoleSObjectFieldMap, roFields);
                    if(!allowedROFields.isEmpty())
                    {
                        formSoql = 'Select ';
                        for(String roField: allowedROFields)
                        {
                            formSoql += roField+', ';
                        }
                        
                        formSoql = formSoql.substring(0, formSoql.length() - 2);
                        formSoql += ' from UserRole where ';
                        
                        roFields = new String[]{'Id'}; 
                        allowedROFields = dacu.getAccessibleFields(sObj, userRoleSObjectFieldMap, roFields);
                        if(!allowedROFields.isEmpty())
                        {
                            for(String roField: allowedROFields)
                            {
                                formSoql += roField+' in :afterBatchSet ';
                            }
                            
                            for(UserRole[] ur: Database.query(formSoql))//[select Name from UserRole where id in : afterBatchMap.keyset()])
                            {
                                for(UserRole urObj: ur)
                                {
                                    showRoleTitleList.add(urObj.Name);
                                }
                            }   
                        }
                    }
                }
                else if(selectedRadio == 'titles')
                {
                    showRoleTitleList = new List<String>();

                    sObj = new User();
                    userSObjectFieldMap = dacu.getFieldMap(sObj);
                    
                    roFields = new String[]{'Title'}; 
                    allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
                    if(!allowedROFields.isEmpty())
                    {
                        formSoql = 'Select ';
                        for(String roField: allowedROFields)
                        {
                            formSoql += roField+', ';
                        }
                        
                        formSoql = formSoql.substring(0, formSoql.length() - 2);
                        formSoql += ' from User where ';
                        
                        roFields = new String[]{'Title'}; 
                        allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
                        if(!allowedROFields.isEmpty())
                        {
                            for(String roField: allowedROFields)
                            {
                                formSoql += roField+' in :afterBatchSet ';
                            }
                            
                            for(User[] u: Database.query(formSoql))//[select Title from User where Title in : afterBatchMap.keyset()])
                            {
                                for(User uObj: u)
                                {
                                    showRoleTitleList.add(uObj.Title);
                                }
                            }
                        }
                    }   
                }
                else if(selectedRadio == 'participants')
                {
                    showRoleTitleList = new List<String>();
                    sObj = new User();
                    userSObjectFieldMap = dacu.getFieldMap(sObj);

                    roFields = new String[]{'Name'}; 
                    allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
                    if(!allowedROFields.isEmpty())
                    {
                        formSoql = 'Select ';
                        for(String roField: allowedROFields)
                        {
                            formSoql += roField+', ';
                        }
                        
                        formSoql = formSoql.substring(0, formSoql.length() - 2);
                        formSoql += ' from User where ';
                        
                        roFields = new String[]{'Id'}; 
                        allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
                        if(!allowedROFields.isEmpty())
                        {
                            for(String roField: allowedROFields)
                            {
                                formSoql += roField+' in :afterBatchSet ';
                            }
                            
                            for(User[] u: Database.query(formSoql))
                            {
                                for(User urObj: u)
                                {
                                    showRoleTitleList.add(urObj.Name);
                                }
                            }
                        }
                    }   
                }
                                
                showSelectedRadioLabel = true;
            }//end of if(batchId != null)
        }
        catch(Exception e)
        {
            Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, e.getMessage()));       
        }
    }//end of constructor
    
    public String cleanXSS(String val)
    {
        val = val.toLowerCase();
        return val; 
    }
    
    private void getUserManagers()
    {
        sObj = new Reporting_Manager__c();
        if(reportManagerSObjectFieldMap.isEmpty())
            reportManagerSObjectFieldMap = dacu.getFieldMap(sObj);
            
        roFields = new String[]{'Reporting_Manager__c'}; 
        allowedROFields = dacu.getAccessibleFields(sObj, reportManagerSObjectFieldMap, roFields);
        if(!allowedROFields.isEmpty())
        {
            formSoql = 'Select ';
            for(String roField: allowedROFields)
            {
                formSoql += roField+', ';
            }
            
            formSoql = formSoql.substring(0, formSoql.length() - 2);
            formSoql += ' from Reporting_Manager__c';
            
            AccessDetails ad = new AccessDetails();            
            Reporting_Manager__c[] rmList = (reporting_manager__c[])ad.fetchRecords(formSoql);
            fieldName = rmList[0].Reporting_Manager__c;
            
            sObj = new User();
            if(userSObjectFieldMap.isEmpty())
                userSObjectFieldMap = dacu.getFieldMap(sObj);
                
            roFields = new String[]{'Id',fieldName}; 
            
            allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
            if(!allowedROFields.isEmpty())
            {
                formSoql = 'Select ';
                for(String roField: allowedROFields)
                {
                    formSoql += roField+', ';
                }
                
                formSoql = formSoql.substring(0, formSoql.length() - 2);
                formSoql += ' from User where ';
                
                roFields = new String[]{'IsActive'}; 
                allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
                if(!allowedROFields.isEmpty())
                {
                    for(String roField: allowedROFields)
                    {
                        formSoql += roField+' = true ';
                    }
                    
                    sObject s = null;
                    for(User[] localUserList: Database.query(formSoql))//Database.query('select Id, '+fieldName+' from User where IsActive = true '))
                    {
                        for(User u: localUserList)
                        {
                            s = u;
                            if(usersManagerMap1.size() < 1000)
                                usersManagerMap1.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap2.size() < 1000)
                                usersManagerMap2.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap3.size() < 1000)
                                usersManagerMap3.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap4.size() < 1000)
                                usersManagerMap4.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap5.size() < 1000)
                                usersManagerMap5.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap6.size() < 1000)
                                usersManagerMap6.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap7.size() < 1000)
                                usersManagerMap7.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap8.size() < 1000)
                                usersManagerMap8.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap9.size() < 1000)
                                usersManagerMap9.put(u.Id, (ID) s.get(fieldName));
                            else if(usersManagerMap10.size() < 1000)
                                usersManagerMap10.put(u.Id, (ID) s.get(fieldName));
                        }
                    }
                }
            }
        }
    }
    
    private without sharing class AccessDetails
    {
    	private SObject[] fetchRecords(String query)
    	{
    		return Database.query(query);
    	}	
    }
    
    public List<SelectOption> getItems()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('roles', 'Roles'));
        options.add(new SelectOption('titles', 'Titles'));
        options.add(new SelectOption('participants', 'Participants'));
        return options;
    }
    
    public List<UserRole> getRoleDetails()
    {
        sObj = new UserRole();
        if(userRoleSObjectFieldMap.isEmpty())
            userRoleSObjectFieldMap = dacu.getFieldMap(sObj);
            
        roFields = new String[]{'Id','Name'}; 
        allowedROFields = dacu.getAccessibleFields(sObj, userRoleSObjectFieldMap, roFields);
        if(!allowedROFields.isEmpty())
        {
            formSoql = 'Select ';
            for(String roField: allowedROFields)
            {
                formSoql += roField+', ';
            }
            
            formSoql = formSoql.substring(0, formSoql.length() - 2);
            formSoql += ' from UserRole limit 1000';
            
            uRoleList = Database.query(formSoql);//[select Id, Name from UserRole limit 1000];
        }       
        return uRoleList;
    }

    public List<User> getTitleDetails()
    {
        sObj = new User();
        if(userSObjectFieldMap.isEmpty())
            userSObjectFieldMap = dacu.getFieldMap(sObj);
            
        roFields = new String[]{'Id', 'Title'}; 
        allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
        if(!allowedROFields.isEmpty())
        {
            formSoql = 'Select ';
            for(String roField: allowedROFields)
            {
                formSoql += roField+', ';
            }
            
            formSoql = formSoql.substring(0, formSoql.length() - 2);
            formSoql += ' from User where ';
            
            roFields = new String[]{'IsActive'}; 
            allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
            if(!allowedROFields.isEmpty())
            {
                for(String roField: allowedROFields)
                {
                    formSoql += roField+' = true limit 1000';
                }
                
                User[] users = Database.query(formSoql);//[select Id, Title from User where isActive = true limit 1000];
                uMap = new Map<String, User>();
                for(User u : users)
                {
                    uMap.put(u.Title, u);
                }       
                uList = uMap.values();
            }
        }
        return uList;
    }
    
    public List<User> getParticipantDetails()
    {
        
        User[] users = null;
        sObj = new User();
        if(userSObjectFieldMap.isEmpty())
            userSObjectFieldMap = dacu.getFieldMap(sObj);
            
        roFields = new String[]{'Id', 'Name'};//, 'User.UserRole.Name'}; 
        allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
                        
        if(!allowedROFields.isEmpty())
        {
            formSoql = 'Select ';
            for(String roField: allowedROFields)
            {
                formSoql += roField+', ';
            }
            
            sObj = new UserRole();
            if(userRoleSObjectFieldMap.isEmpty())
                userRoleSObjectFieldMap = dacu.getFieldMap(sObj);
            roFields = new String[]{'Name'};//, 'UserRole.Name'}; 
            allowedROFields = dacu.getAccessibleFields(sObj, userRoleSObjectFieldMap, roFields);
            for(String roField: allowedROFields)
            {
                if(roField.equalsIgnoreCase('Name'))
                    formSoql += ' UserRole.Name, ';
            }
            
            formSoql = formSoql.substring(0, formSoql.length() - 2);
            formSoql += ' from User where ';
            roFields = new String[]{'IsActive'}; 
            allowedROFields = dacu.getAccessibleFields(sObj, userSObjectFieldMap, roFields);
            if(!allowedROFields.isEmpty())
            {
                for(String roField: allowedROFields)
                {
                    formSoql += roField+' = true limit 1000';
                }
                users = Database.query(formSoql);//[select Id, Name, UserRole.Name from User where isActive = true limit 1000];
            }
        }
        return users;
    }

    public List<SelectOption> getDetails()
    {
        return optionDetails;
    }

    public List<SelectOption> getDetails2()
    {
        return optionDetails2;
    }

    //This code executes in Batch mode
    public PageReference saveSelectedDetails()
    {
        SObject sObj = new BatchedUser__c();
        SObject bObj = new Batch__c();
        //Enters only if user has permission to create BatchedUser__c and Batch__c object
        //Not performing further FLS checks as this code executes in Batch
        if(dacu.isCreateableObjectByUser(sObj).equalsIgnoreCase('success') && dacu.isCreateableObjectByUser(bObj).equalsIgnoreCase('success'))
        {
            try
            {
                BatchedUser__c bu = null;
                Batch__c batch = null;
                batchedUserList = new List<BatchedUser__c>();
                if(batchId == null)
                {
                    batch = new Batch__c();
                    insert batch;
                    batchId = batch.id; 
                }
                
                if(selectedRadio == 'roles')
                {
                    Map<ID, ID> roleIDMap = new Map<ID, ID>();
                    for(String s: selectedVals)
                        roleIDMap.put(s, s);
                    for(String s: selectedVals2)
                        roleIDMap.put(s, s);
                    
                    for(User[] users: [select Id, Name, UserRole.Id, UserRole.Name, Title, ManagerId from User where UserRole.Id in :roleIDMap.keyset() and IsActive = true])
                    {
                        for(User u: users)
                        {
                            bu = new BatchedUser__c();
                            bu.UserId__c = u.id;
                            bu.UserRoleId__c = u.UserRole.id;
                            bu.Batchid__c = batchId;
                            batchedUserList.add(bu);
    
                            if(batchedUserList.size() == 200)
                            {
                                insert batchedUserList;
                                batchedUserList.clear();
                            }
                        }
                    }
                                
                }//end of if(selectedRadio == 'Roles')
                else if(selectedRadio == 'titles')
                {
                    Map<String, String> titleIDMap = new Map<String, String>();
                    for(String s: selectedVals)
                        titleIDMap.put(s, s);
                    for(String s: selectedVals2)
                        titleIDMap.put(s, s);
                    
                    for(User[] users: [select Id, Name, UserRole.Name, Title, ManagerId from User where Title in :titleIDMap.keyset() and IsActive = true])
                    {
                        for(User u: users)
                        {
    
                            bu = new BatchedUser__c();
                            bu.UserId__c = u.id;
                            bu.User_Title__c = u.Title;
                            bu.Batchid__c = batchId;
                            batchedUserList.add(bu);
                            if(batchedUserList.size() == 200)
                            {
                                insert batchedUserList;
                                batchedUserList.clear();
                                
                            }
                        }
                    }
                }//end of if(selectedRadio == 'titles')
                else
                {
                    Map<String, String> participantIDMap = new Map<String, String>();
                    for(String s: selectedVals)
                        participantIDMap.put(s, s);
                    for(String s: selectedVals2)
                        participantIDMap.put(s, s);
                    
                    for(User[] users: [select Id, UserRole.Id, UserRole.Name, Title, Name, ManagerId from User where Id in :participantIDMap.keyset() and IsActive = true])
                    {
                        for(User u: users)
                        {
    
                            bu = new BatchedUser__c();
                            bu.UserId__c = u.id;
                            bu.User_Title__c = u.Title;
                            bu.UserRoleId__c = u.UserRole.id;
                            bu.Batchid__c = batchId;
                            batchedUserList.add(bu);
                            if(batchedUserList.size() == 200)
                            {
                                insert batchedUserList;
                                batchedUserList.clear();
                                
                            }
                        }
                    }
                }//end of if(selectedRadio == 'titles')
    
                if(batchedUserList.size() > 0)
                {
                    insert batchedUserList;
                    batchedUserList.clear();
                }
            
            }
            catch(Exception e)
            {
                Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, '---'+e.getMessage()));
            }
            PageReference pr = new PageReference('/apex/Batch_Details_for_Plan_Distribution?srval='+selectedRadio+'&bcId='+batchId);
            pr.setRedirect(true);
            return pr;
        }
        return null;
    }
    
    public PageReference cancel()
    {
        PageReference pr = new PageReference('/apex/Batch_Details_for_Plan_Distribution?srval='+selectedRadio);
        pr.setRedirect(true);
        return pr;
    }

    public PageReference navigateToGetDetails()
    {
        PageReference pr = new PageReference('/apex/Select_Details_For_Distribution?srval='+selectedRadio);
        pr.setRedirect(true);
        return pr;
    }

    //This method code executes in Batch process. 
    public PageReference startDistribution()
    {
        if(pdi.Effective_Start_Date__c == null)
        {
            Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, 'Please enter Required Acceptance Date.'));
            return null;    
        }
        
        SObject bObj = new Batch__c();
        SObject scObj = new Sales_Contract__c();
        DataAccessControlUtil dacu = new DataAccessControlUtil();
        
        //Enters only if User has permission to create Sales_Contract__c object and Update permission for Sales_Contract__c and Batch__c objects
        //Not performing further FLS checks as this code executes in Batch
        if(dacu.isCreateableObjectByUser(scObj).equalsIgnoreCase('success') && dacu.isUpdateableObjectByUser(scObj).equalsIgnoreCase('success') && dacu.isUpdateableObjectByUser(bObj).equalsIgnoreCase('success'))
        {
            
            CallidusDataSource__c[] updateCdsList = new CallidusDataSource__c[]{};
            Map<ID, CallidusDataSource__c> cdsMap = new Map<ID, CallidusDataSource__c>();  
            contractsList = new Sales_Contract__c[]{};
            showContractsList = new Sales_Contract__c[]{};
            Sales_Contract__c sc = null;
            Date dt = Date.today();
            Task[] tasksList = new Task[]{};
            Sales_Contract__Share[] scShareList  = new Sales_Contract__Share[]{};
            
            participantsWithNoManagerAssigned = new List<User>();   
            inactiveParticipants = new List<User>(); 
            
            Set<Id> bUserList = batchedUserMap.keyset();    
            Set<Id> bUserList1 = batchedUserMap1.keyset();  
            Set<Id> bUserList2 = batchedUserMap2.keyset();  
            Set<Id> bUserList3 = batchedUserMap3.keyset();  
            Set<Id> bUserList4 = batchedUserMap4.keyset();  
            SObject so = null;
            for(User[] localUserList: Database.query('select Id, Name, FirstName, LastName,UserRole.Name, Title, IsActive, '+fieldName+' from User where id in :bUserList or id in :bUserList1 or id in :bUserList2 or id in :bUserList3 or id in :bUserList4 '))
            {
                for(User u: localUserList)
                {
                    so = u;
                    if(so.get(fieldName) == null)
                        participantsWithNoManagerAssigned.add(u);
                    if(so.get('IsActive') == false)
                        inactiveParticipants.add(u);
                }
            }
    
            Integer totalContracts = 0;
            Integer planDocsCreated = 0;
            DateTime dtn = DateTime.now();
            
            Set<String> batchFieldsToBeUpdatedList = new Set<String>{'Status__c', 'StartTime__c', 'EndTime__c', 'TotalContracts__c', 'RemainingContracts__c'};
            
            String constructSoql = '';
            try
            {
                batchObject = [SELECT Name, Status__c, StartTime__c, EndTime__c, TotalContracts__c, RemainingContracts__c from Batch__c b where b.Id = :batchId limit 1];
                batchObject.StartTime__c = Datetime.now();
                batchObject.Name = 'Plan Document Generation '+'_'+dtn;
                batchObject.status__c = 'InProgress';
                
                update batchObject;
                            
                Approvers__c[] approver = [select Final_Approver__c, Final_Approver_Date__c,  Level1__c, Level2__c, Level3__c, Level4__c, Level5__c, Level6__c, Level7__c, Level8__c, Level9__c, Level10__c, Level11__c, Level12__c, Level13__c, Level14__c, Level15__c, Level1_Due_Date__c, Level2_Due_Date__c, Level3_Due_Date__c, Level4_Due_Date__c, Level5_Due_Date__c, Level6_Due_Date__c, Level7_Due_Date__c, Level8_Due_Date__c, Level9_Due_Date__c, Level10_Due_Date__c, Level11_Due_Date__c, Level12_Due_Date__c, Level13_Due_Date__c, Level14_Due_Date__c, Level15_Due_Date__c from Approvers__c where Template__c = null order by CreatedDate desc limit 1];
                Boolean flag = false;
    
                if(participantsWithNoManagerAssigned.size() > 0)
                {
                    for(User u: participantsWithNoManagerAssigned)
                    {
                        batchedUserMap.remove(u.id);                    
                        batchedUserMap1.remove(u.id);                   
                        batchedUserMap2.remove(u.id);
                        batchedUserMap3.remove(u.id);
                        batchedUserMap4.remove(u.id);
                    }
                }
                
                if(inactiveParticipants.size() > 0)
                {
                    for(User u: inactiveParticipants)
                    {
                        batchedUserMap.remove(u.id);                    
                        batchedUserMap1.remove(u.id);                   
                        batchedUserMap2.remove(u.id);
                        batchedUserMap3.remove(u.id);
                        batchedUserMap4.remove(u.id);
                    }
                }
                
                Boolean checkNoAttachFlag = false;
                for(CallidusDataSource__c[] cds : [SELECT Id, Name, FirstName__c, LastName__c, UserID__c, UserRoleId__c, UserRoleName__c, User_Title__c, In_Use_Attachments__c, Latest_Attachments__c, Can_Accept_Plan__c, Email_Notification_1__c, Email_Notification_2__c, Email_Notification_3__c, Instruction__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c, Plan_Comment__c, Instruction_1__c, Instruction_2__c, Instruction_3__c, Instruction_4__c, Instruction_5__c, Plan_Accept_Message__c, (select id, name from Attachments order by createddate desc limit 5) FROM CallidusDataSource__c dsc where dsc.UserId__c in : batchedUserMap.keyset() or dsc.UserId__c in : batchedUserMap1.keyset() or dsc.UserId__c in : batchedUserMap2.keyset() or dsc.UserId__c in : batchedUserMap3.keyset() or dsc.UserId__c in : batchedUserMap4.keyset()])
                {
                    for(CallidusDataSource__c dsc: cds)
                    {
                        flag = false;
                        String attachId = '';
                        dsc.Latest_Attachments__c = null;
                        
                        if(planComment.length() > 0)
                            dsc.Plan_Comment__c = planComment;
                                            
                        for(Attachment a: dsc.Attachments)
                        {
                            if(dsc.In_Use_Attachments__c != null)
                            {
                                if(dsc.In_Use_Attachments__c.contains(a.Id) == false)
                                {
                                    if(a.Name.toLowerCase().indexOf('plan') != -1)
                                        attachId = a.Id;
                                                                            
                                    dsc.In_Use_Attachments__c += ','+a.Id;
                                    if(dsc.Latest_Attachments__c == null)
                                    {
                                        dsc.Latest_Attachments__c = a.Id;
                                    }
                                    else
                                        dsc.Latest_Attachments__c += ','+a.Id;
    
                                    if(!flag)
                                        flag = true;
                                }//end of if(dsc.In_Use.... == -1)
                                else
                                    checkNoAttachFlag = true;            
                            }       
                            else
                            {
                                if(a.Name.toLowerCase().indexOf('plan') != -1)
                                    attachId = a.Id;
                                    
                                dsc.In_Use_Attachments__c = a.Id;
    
                                if(dsc.Latest_Attachments__c == null)
                                    dsc.Latest_Attachments__c = a.Id;
                                else
                                    dsc.Latest_Attachments__c += ','+a.Id;
    
                                flag = true;
                            }
                            if(attachId.length() == 0)  
                                attachId = a.Id;
                                
                        }//end of for(Attachment a:)
                        
                        totalContracts++;
                        if(flag)
                        {
                            flag = false;
                            sc = new Sales_Contract__c();
                            sc.Plan_Document_Name__c = dsc.FirstName__c+' '+dsc.LastName__c+' '+dt.month()+'/'+dt.day()+'/'+dt.year();
                            
                            sc.FirstName__c = dsc.FirstName__c;
                            sc.LastName__c = dsc.LastName__c;
                            sc.UserRoleId__c = dsc.UserRoleId__c;
                            sc.UserID__c = dsc.UserID__c; 
                            sc.User_ID__c = dsc.UserID__c;
                            
                            sc.UserRoleName__c = dsc.UserRoleName__c;
                            sc.User_Title__c = dsc.User_Title__c;
                                        
                            sc.Generated_Date__c = dt;
                            sc.BatchID__c = batchId;
                            sc.Batch__c = batchId;         
                            sc.RequiredReturnDate__c = pdi.Effective_Start_Date__c;
                            sc.AttachmentID__c = attachId;
                            sc.Plan_Attachments__c = dsc.Latest_Attachments__c;
                            
                            sc.Plan_Accept_Message__c = dsc.Plan_Accept_Message__c;
                            sc.Email_Notification_1__c = dsc.Email_Notification_1__c;
                            sc.Email_Notification_2__c = dsc.Email_Notification_2__c;
                            sc.Email_Notification_3__c = dsc.Email_Notification_3__c;
                            sc.Can_Accept_Plan__c = dsc.Can_Accept_Plan__c;
                            sc.Instruction__c = dsc.Instruction__c;
                            sc.Instruction_1__c = dsc.Instruction_1__c;
                            sc.Instruction_2__c = dsc.Instruction_2__c;
                            sc.Instruction_3__c = dsc.Instruction_3__c;
                            sc.Instruction_4__c = dsc.Instruction_4__c;
                            sc.Instruction_5__c = dsc.Instruction_5__c;
                            sc.Value1__c = dsc.Value1__c;
                            sc.Value2__c = dsc.Value2__c;
                            sc.Value3__c = dsc.Value3__c;
                            sc.Value4__c = dsc.Value4__c;
                            sc.Value5__c = dsc.Value5__c;
                            sc.Value6__c = dsc.Value6__c;
                            sc.Value7__c = dsc.Value7__c;
                            sc.Value8__c = dsc.Value8__c;
                            sc.Value9__c = dsc.Value9__c;
                            sc.Value10__c = dsc.Value10__c;
                            sc.Value11__c = dsc.Value11__c;
                            sc.Value12__c = dsc.Value12__c;
                            sc.Value13__c = dsc.Value13__c;
                            sc.Value14__c = dsc.Value14__c;
                            sc.Value15__c = dsc.Value15__c;
                            sc.Value16__c = dsc.Value16__c;
                            sc.Value17__c = dsc.Value17__c;
                            sc.Value18__c = dsc.Value18__c;
                            sc.Value19__c = dsc.Value19__c;
                            sc.Value20__c = dsc.Value20__c;
                            sc.Value21__c = dsc.Value21__c;
                            sc.Value22__c = dsc.Value22__c;
                            sc.Value23__c = dsc.Value23__c;
                            sc.Value24__c = dsc.Value24__c;
                            sc.Value25__c = dsc.Value25__c;
                            sc.Value26__c = dsc.Value26__c;
                            sc.Value27__c = dsc.Value27__c;
                            sc.Value28__c = dsc.Value28__c;
                            sc.Value29__c = dsc.Value29__c;
                            sc.Value30__c = dsc.Value30__c;
                            sc.Plan_Comment__c = dsc.Plan_Comment__c;
                            
                            if(approver.size() > 0)
                            {
                                sc = populateSalesContractLevels(sc, approver[0]);
                                if(sc.Level1__c != null)
                                {
                                    sc.Status__c = 'Distributed';
                                }//end of if(sc.Level1__c != null)
                                                    
                            }//end of if(approver.size() > 0)
                            else
                                sc.Status__c = 'Published';
                                
                            contractsList.add(sc);
                            cdsMap.put(dsc.id, dsc);
                            
                            if(cdsMap.size() == 200)
                            {
                                updateCdsList = cdsMap.values();
                                update updateCdsList;
                                cdsMap.clear();
                                updateCdsList.clear();
                            }
                            
                            if(contractsList.size() == 200)
                            {
                                insert contractsList;
                                planDocsCreated += 200;
                                for(Sales_Contract__c s:contractsList)
                                {
                                    Sales_Contract__History history = new Sales_Contract__History(ParentId = s.Id);
                                    Task t = new Task();
                                    t.WhatId = s.Id;
                                    if(s.Status__c == 'Distributed')
                                    {
                                        t.OwnerId = s.Level1__c;
                                        t.Subject = 'Plan Document Distributed';
                                        t.Description = 'Plan Document Distributed.';
                                        t.ActivityDate = s.Level1_Due_Date__c;//Date.valueof(requiredReturnDate);
                                        String remDateTime = s.Level1_Due_Date__c+' 08:00:00';
                                        t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                                    }
                                    else
                                    {
                                        t.OwnerId = s.UserID__c;
                                        t.Subject = 'Plan Document Published';
                                        t.Description = 'Plan Document Published.';
                                        t.ActivityDate = s.RequiredReturnDate__c;//Date.valueof(requiredReturnDate);
                                        String remDateTime = s.RequiredReturnDate__c+' 08:00:00';
                                        t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                                    }
                                    t.Status = 'NotStarted';
                                    t.Type = 'Email';
                                    t.IsReminderSet = true;
                                    t.Priority = 'Normal';
                                    
                                    tasksList.add(t);
        
                                    if(s.Status__c == 'Distributed')
                                    {
                                        Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
                                        request.setObjectId(s.Id);
                                        Approval.ProcessResult result = Approval.process(request);
                                        
                                    }   
                                    if(showContractsList.size() <= 1000)
                                    {
                                        showContractsList.add(s);
                                    }
                                }
                                insert tasksList;
                                
                                contractsList.clear();
                                tasksList.clear();
                            }
                        }//end of if(flag)                
                    }//end of for(CallidusDataSource__c dsc: cds)
                    
                }//end of for(CallidusDataSource__c[] cds : [SELECT
                
                if(cdsMap.size() > 0)
                {
                    updateCdsList = cdsMap.values();
                    update updateCdsList;
                    cdsMap.clear();
                    updateCdsList.clear();
                }
             
                if(contractsList.size() > 0)
                {
                    insert contractsList;
                    planDocsCreated += contractsList.size();
                    
                    for(Sales_Contract__c s:contractsList)
                    {
                        Sales_Contract__History history = new Sales_Contract__History(ParentId = s.Id);
                        Task t = new Task();
                        t.WhatId = s.Id;
                        if(s.Status__c == 'Distributed')
                        {
                            t.OwnerId = s.Level1__c;
                            t.Subject = 'Plan Document Distributed';
                            t.Description = 'Plan Document Distributed.';
                            t.ActivityDate = s.Level1_Due_Date__c;//Date.valueof(requiredReturnDate);
                            String remDateTime = s.Level1_Due_Date__c+' 08:00:00';
                            t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                        }
                        else
                        {
                            t.OwnerId = s.UserID__c;
                            t.Subject = 'Plan Document Published';
                            t.Description = 'Plan Document Published.';
                            t.ActivityDate = s.RequiredReturnDate__c;//Date.valueof(requiredReturnDate);
                            String remDateTime = s.RequiredReturnDate__c+' 08:00:00';
                            t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                        }
                        t.Status = 'NotStarted';
                        t.Type = 'Email';
                        t.IsReminderSet = true;
                        t.Priority = 'Normal';
                        
                        tasksList.add(t);
    
                        if(s.Status__c == 'Distributed')
                        {
                            Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
                            request.setObjectId(s.Id);
                            Approval.ProcessResult result = Approval.process(request);
                        }   
                        if(showContractsList.size() <= 1000)
                        {
                            showContractsList.add(s);
                        }
                    }
                    insert tasksList;
        
                    contractsList.clear();
                    tasksList.clear();
                }
        
                String subject = 'Plan Document generation '+dtn+' not successful for some users.';
                String textBody = 'Plan Document generation '+dtn+' not successful for some users.';
                String htmlBody = 'Following is the list of users for whom Plan Document generation '+dtn+' was not successful, because their Manager value is not set on their User Record.';
                htmlBody += '<br>';
                for(User u: participantsWithNoManagerAssigned)
                {
                    htmlBody += '<br>';
                    htmlBody += u.FirstName+', '+u.LastName;
                }
                htmlBody += '<br>';
                htmlBody += '<br>';
                htmlBody += 'Please work with your System Administrator to configure before your next plan document generation.';
                
                if(showContractsList.size() > 0)
                {
                    batchObject.Status__c = 'Completed';
                    batchObject.EndTime__c = datetime.now();
                    batchObject.TotalContracts__c = planDocsCreated;
                    batchObject.RequiredReturnDate__c = pdi.Effective_Start_Date__c;
                    batchObject.RemainingContracts__c = totalContracts - planDocsCreated;
                    update batchObject;
                    batchObject.Status__c = 'Distributed';
                    update batchObject;
                    
                    showContractsListBool = true;
                    isBatchGenerated = true;
                    isNotBatchGenerated = false;

                    if(participantsWithNoManagerAssigned.size() > 0)
                    {
                        GenerateUtil.sendMailToUser(UserInfo.getUserId(), subject, textBody, htmlBody);
                        Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, 'Plan Distribution was not successful for some of the Users.'));
                    }
                    else if(participantsWithNoManagerAssigned.size() == 0 && inactiveParticipants.size() == 0)
                        Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, 'Plan Distribution was successful.'));
                }
                else
                {
                    if(participantsWithNoManagerAssigned.size() > 0 && checkNoAttachFlag)
                    {
                        Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, 'There is no Manager value set in the User record for some Users and there are no Attachments associated for some Users.'));
                        GenerateUtil.sendMailToUser(UserInfo.getUserId(), subject, textBody, htmlBody);
                    }
                    else if(participantsWithNoManagerAssigned.size() > 0)
                    {
                        Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, 'There is no Manager value set in the User record.'));
                        GenerateUtil.sendMailToUser(UserInfo.getUserId(), subject, textBody, htmlBody);
                    }
                    else if(checkNoAttachFlag)
                        Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, 'Plan Distribution failed as Attachments are not associated to the Participants.'));
                }

                subject = 'Plan Distribution for some users was  not done as they are inactive.';
                textBody = 'Plan Distribution for some users was  not done as they are inactive.';
                htmlBody = 'Following is the list of Inactive users for whom Plan Document distribution was not done.';
                htmlBody += '<br>';
                for(User u: inactiveParticipants)
                {
                    htmlBody += '<br>';
                    htmlBody += u.FirstName+', '+u.LastName;
                }
                htmlBody += '<br>';
                htmlBody += '<br>';
                htmlBody += 'Please work with your System Administrator to configure before your next plan document distribution.';
                
                if(inactiveParticipants.size() > 0)
                {
                    Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, 'Plan Distribution was not successful for some of the Users as they are inactive.'));
                    GenerateUtil.sendMailToUser(UserInfo.getUserId(), subject, textBody, htmlBody);
                }

            }catch(Exception e)
            {
                Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.info, e.getMessage()));
            }       

	        PlanDistributionBatch pdb = new PlanDistributionBatch(batchedUserMap.keyset(),batchedUserMap1.keyset(),batchedUserMap2.keyset(),batchedUserMap3.keyset(),batchedUserMap4.keyset());
	        
	        Database.executeBatch(pdb, 1);
	        
        }
        
        return null;
    }
    
    private ID getManagerId(Id mId)
    {
        ID managerId = usersManagerMap1.get(mId);
        if(managerId == null)
            managerId = usersManagerMap2.get(mId);
        if(managerId == null)
            managerId = usersManagerMap3.get(mId);
        if(managerId == null)
            managerId = usersManagerMap4.get(mId);
        if(managerId == null)
            managerId = usersManagerMap5.get(mId);
        if(managerId == null)
            managerId = usersManagerMap6.get(mId);
        if(managerId == null)
            managerId = usersManagerMap7.get(mId);
        if(managerId == null)
            managerId = usersManagerMap8.get(mId);
        if(managerId == null)
            managerId = usersManagerMap9.get(mId);
        if(managerId == null)
            managerId = usersManagerMap10.get(mId);
            
        return managerId;
    }
    
    private Sales_Contract__c populateSalesContractLevels(Sales_Contract__c sc, Approvers__c approver)
    {
        ID managerId = null;
        if(approver.Level1__c != null)
        {
            managerId = getManagerId(sc.UserID__c);
                
            if(managerId != null)
            {
                sc.Level1__c = managerId;
                sc.Level1_Due_Date__c = approver.Level1_Due_Date__c;
            }
            
        }
        
        if(approver.Level2__c != null)
        {
            managerId = getManagerId(managerId);
                
            if(managerId != null)
            {
                sc.Level2__c = managerId;
                sc.Level2_Due_Date__c = approver.Level2_Due_Date__c;
            }
        }
        if(approver.Level3__c != null)
        {
            managerId = getManagerId(managerId);
                
            if(managerId != null)
            {
                sc.Level3__c = managerId;
                sc.Level3_Due_Date__c = approver.Level3_Due_Date__c;
            }
        }
        if(approver.Level4__c != null)
        {
            managerId = getManagerId(managerId);
                
            if(managerId != null)
            {
                sc.Level4__c = managerId;
                sc.Level4_Due_Date__c = approver.Level4_Due_Date__c;
            }
        }
        if(approver.Level5__c != null)
        {
            managerId = getManagerId(managerId);
                
            if(managerId != null)
            {
                sc.Level5__c = managerId;
                sc.Level5_Due_Date__c = approver.Level5_Due_Date__c;
            }
        }
        
/*          if(approver.Level6__c != null)
            {
                sc.Level6__c = user[0].managerId;
                sc.Level6_Due_Date__c = approver.Level6_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level7__c != null)
            {
                sc.Level7__c = user[0].managerId;
                sc.Level7_Due_Date__c = approver.Level7_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level8__c != null)
            {
                sc.Level8__c = user[0].managerId;
                sc.Level8_Due_Date__c = approver.Level8_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level9__c != null)
            {
                sc.Level9__c = user[0].managerId;
                sc.Level9_Due_Date__c = approver.Level9_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level10__c != null)
            {
                sc.Level10__c = user[0].managerId;
                sc.Level10_Due_Date__c = approver.Level10_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level11__c != null)
            {
                sc.Level11__c = user[0].managerId;
                sc.Level11_Due_Date__c = approver.Level11_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level12__c != null)
            {
                sc.Level12__c = user[0].managerId;
                sc.Level12_Due_Date__c = approver.Level12_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level13__c != null)
            {
                sc.Level13__c = user[0].managerId;
                sc.Level13_Due_Date__c = approver.Level13_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level14__c != null)
            {
                sc.Level14__c = user[0].managerId;
                sc.Level14_Due_Date__c = approver.Level14_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }
            if(approver.Level15__c != null)
            {
                sc.Level15__c = user[0].managerId;
                sc.Level15_Due_Date__c = approver.Level15_Due_Date__c;
                if(testVar == '')
                    user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
            }*/
        if(approver.Final_Approver__c != null)
        {
            sc.Final_Approver__c = approver.Final_Approver__c;
            sc.Final_Approver_Date__c = approver.Final_Approver_Date__c;
        }
        
        return sc;
    }//end of public static populateSalesContractLevels()

    
    static testMethod void testGenerateUtilForPlanDistribution() 
    {
    	try
    	{
	        PageReference pg = Page.Batch_Details_for_Plan_Distribution;
	        
	        Test.setCurrentPage(pg);
	        Test.startTest();
	        pg.getParameters().put('srval', null);
	        Batch__c b = new Batch__c(Status__c = 'In Progress');
	        insert b;
	        
	        User u = new User(Lastname = 'enduser', Username = 'enduser1@gmail.com', Email = 'enduser@gmail.com', Alias = 'enduser', CommunityNickname = 'euser', UserRoleId = UserInfo.getUserRoleId(), TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', EmailEncodingKey = 'ISO-8859-1', ProfileId = UserInfo.getProfileId(), LanguageLocaleKey = 'en_US', ManagerId = UserInfo.getUserId(), Title = 'Manager');
	        try
	        {
	            insert u;
	            
	        }
	        catch(Exception e){}
	        
	        CallidusDataSource__c cds = new CallidusDataSource__c(UserId__c = u.Id);
	        insert cds;
	        Attachment a = new Attachment(name = 'TestPlan', ContentType='application/pdf', Body = Blob.valueOf('<html><body>This is an Attachment</body></html>'), ParentId = cds.Id);
	        insert a;
	        
	        BatchedUser__c bu = new BatchedUser__c(UserRoleId__c = u.UserRoleId,User_Title__c = u.Title,UserId__c = u.Id, BatchId__c = b.Id);
	        insert bu;
	
	        pg.getParameters().put('bcId', b.id);
	        pg.getParameters().put('srval', 'roles');
	
	        GenerateUtilForPlanDistribution g = new GenerateUtilForPlanDistribution();
	        g.selectedVals = new String[]{UserInfo.getUserRoleId()};
	                
	        g = new GenerateUtilForPlanDistribution();
	        g.getItems();
	        g.getRoleDetails();
	        g.getTitleDetails();
	        g.cancel();
	        g.getParticipantDetails();
	        g.saveSelectedDetails();    
	        g.getUserManagers();
	        g.startDistribution();
	
	        g.getDetails();
	        g.getDetails2();
	        g.cleanXSS('val');
	        g.navigateToGetDetails();
	
	        Test.stopTest();
    	}
    	catch(exception e){}
    }

    static testMethod void testGenerateUtilForPlanDistribution1() 
    {
    	try
    	{
	        PageReference pg = Page.Batch_Details_for_Plan_Distribution;
	        
	        Test.setCurrentPage(pg);
	        Test.startTest();
	        Batch__c b = new Batch__c(Status__c = 'In Progress');
	        insert b;
	        
	        User u = new User(Lastname = 'enduser', Username = 'enduser1@gmail.com', Email = 'enduser@gmail.com', Alias = 'enduser', CommunityNickname = 'euser', UserRoleId = UserInfo.getUserRoleId(), TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', EmailEncodingKey = 'ISO-8859-1', ProfileId = UserInfo.getProfileId(), LanguageLocaleKey = 'en_US', ManagerId = UserInfo.getUserId(), Title = 'Manager');
	        try
	        {
	            insert u;
	        }
	        catch(Exception e){}
	        CallidusDataSource__c cds = new CallidusDataSource__c(UserId__c = u.Id);
	        insert cds;
	        Attachment a = new Attachment(name = 'TestPlan', ContentType='application/pdf', Body = Blob.valueOf('<html><body>This is an Attachment</body></html>'), ParentId = cds.Id);
	        insert a;
	        
	        BatchedUser__c bu = new BatchedUser__c(UserRoleId__c = u.UserRoleId,User_Title__c = u.Title,UserId__c = u.Id, BatchId__c = b.Id);
	        insert bu;
	        pg.getParameters().put('bcId', b.id);
	
	        pg.getParameters().put('srval', 'titles');  
	            
	        GenerateUtilForPlanDistribution g = new GenerateUtilForPlanDistribution();
	        g.selectedVals = new String[]{'CEO'};
	        g.getItems();
	        g.getRoleDetails();
	        g.getTitleDetails();
	        g.cancel();
	        g.getParticipantDetails();
	        g.saveSelectedDetails();    
	        g.getUserManagers();
	        g.startDistribution();
	
	        g.getDetails();
	        g.getDetails2();
	        g.cleanXSS('val');
	        g.navigateToGetDetails();
	
	        Test.stopTest();
    	}
    	catch(exception e){}
    }
    
    static testMethod void testGenerateUtilForPlanDistribution2() 
    {
    	try
    	{
	        PageReference pg = Page.Batch_Details_for_Plan_Distribution;
	        
	        Test.setCurrentPage(pg);
	        Test.startTest();
	        Batch__c b = new Batch__c(Status__c = 'In Progress');
	        insert b;
	        
	        User u = new User(Lastname = 'enduser', Username = 'enduser1@gmail.com', Email = 'enduser@gmail.com', Alias = 'enduser', CommunityNickname = 'euser', UserRoleId = UserInfo.getUserRoleId(), TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', EmailEncodingKey = 'ISO-8859-1', ProfileId = UserInfo.getProfileId(), LanguageLocaleKey = 'en_US', ManagerId = UserInfo.getUserId(), Title = 'Manager');
	        try
	        {
	            insert u;
	        }
	        catch(Exception e){}
	        CallidusDataSource__c cds = new CallidusDataSource__c(UserId__c = u.Id);
	        insert cds;
	        Attachment a = new Attachment(name = 'TestPlan', ContentType='application/pdf', Body = Blob.valueOf('<html><body>This is an Attachment</body></html>'), ParentId = cds.Id);
	        insert a;
	        
	        BatchedUser__c bu = new BatchedUser__c(UserRoleId__c = u.UserRoleId,User_Title__c = u.Title,UserId__c = u.Id, BatchId__c = b.Id);
	        insert bu;
	
	        pg.getParameters().put('bcId', b.id);
	
	        pg.getParameters().put('srval', 'participants');        
	        GenerateUtilForPlanDistribution g = new GenerateUtilForPlanDistribution();
	        g.selectedVals = new String[]{UserInfo.getUserId()};
	        g.getItems();
	        g.getRoleDetails();
	        g.getTitleDetails();
	        g.cancel();
	        g.getParticipantDetails();
	        g.saveSelectedDetails();    
	        g.getUserManagers();
	        g.startDistribution();
	
	        g.getDetails();
	        g.getDetails2();
	        g.cleanXSS('val');
	        g.navigateToGetDetails();
	
	
	        Test.stopTest();
    	}
    	catch(exception e){}
    }

    static testMethod void testGenerateUtilForPlanDistribution3() 
    {
    	try
    	{
	        PageReference pg = Page.Batch_Details_for_Plan_Distribution;
	        
	        Test.setCurrentPage(pg);
	        Test.startTest();
	        Batch__c b = new Batch__c(Status__c = 'In Progress');
	        insert b;
	        
	        User u = new User(Lastname = 'enduser', Username = 'enduser1@gmail.com', Email = 'enduser@gmail.com', Alias = 'enduser', CommunityNickname = 'euser', UserRoleId = UserInfo.getUserRoleId(), TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', EmailEncodingKey = 'ISO-8859-1', ProfileId = UserInfo.getProfileId(), LanguageLocaleKey = 'en_US', ManagerId = UserInfo.getUserId(), Title = 'Manager');
	        try
	        {
	            insert u;
	        }
	        catch(Exception e){}
	        CallidusDataSource__c cds = new CallidusDataSource__c(UserId__c = u.Id);
	        insert cds;
	        Attachment a = new Attachment(name = 'TestPlan', ContentType='application/pdf', Body = Blob.valueOf('<html><body>This is an Attachment</body></html>'), ParentId = cds.Id);
	        insert a;
	        
	        BatchedUser__c bu = new BatchedUser__c(UserRoleId__c = u.UserRoleId,User_Title__c = u.Title,UserId__c = u.Id, BatchId__c = b.Id);
	        insert bu;
	        pg.getParameters().put('bcId', null);
	
	
	        pg.getParameters().put('srval', 'participants');        
	        
	        GenerateUtilForPlanDistribution g = new GenerateUtilForPlanDistribution();
	        g.selectedVals = new String[]{UserInfo.getUserId()};
	        g.getItems();
	        g.getRoleDetails();
	        g.getTitleDetails();
	        g.cancel();
	        g.getParticipantDetails();
	        g.saveSelectedDetails();    
	        g.getUserManagers();
	        g.startDistribution();
	
	        g.getDetails();
	        g.getDetails2();
	        g.cleanXSS('val');
	        g.navigateToGetDetails();
	
	        Test.stopTest();
    	}
    	catch(exception e){}
    }


    static testMethod void testGenerateUtilForPlanDistribution4() 
    {
    	try
    	{
	        PageReference pg = Page.Batch_Details_for_Plan_Distribution;
	        
	        Test.setCurrentPage(pg);
	        Test.startTest();
	        Batch__c b = new Batch__c(Status__c = 'In Progress');
	        insert b;
	        
	        User u = new User(Lastname = 'enduser0', Username = 'enduser1@gmail.com', Email = 'enduser@gmail.com', Alias = 'enduser', CommunityNickname = 'euser', UserRoleId = UserInfo.getUserRoleId(), TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', EmailEncodingKey = 'ISO-8859-1', ProfileId = UserInfo.getProfileId(), LanguageLocaleKey = 'en_US', ManagerId = UserInfo.getUserId(), Title = 'Manager');
	        try
	        {
	            insert u;
	        }
	        catch(Exception e){}
	        CallidusDataSource__c cds = new CallidusDataSource__c(UserId__c = u.Id);
	        insert cds;
	        Attachment a = new Attachment(name = 'TestPlan', ContentType='application/pdf', Body = Blob.valueOf('<html><body>This is an Attachment</body></html>'), ParentId = cds.Id);
	        insert a;
	        
	        BatchedUser__c bu = new BatchedUser__c(UserRoleId__c = u.UserRoleId,User_Title__c = u.Title,UserId__c = u.Id, BatchId__c = b.Id);
	        insert bu;
	        pg.getParameters().put('bcId', null);
	
	
	        pg.getParameters().put('srval', 'Participants');        
	        
	        GenerateUtilForPlanDistribution g = new GenerateUtilForPlanDistribution();
	        g.selectedVals = new String[]{UserInfo.getUserId()};
	        g.getItems();
	        g.getRoleDetails();
	        g.getTitleDetails();
	        g.cancel();
	        g.getParticipantDetails();
	        g.saveSelectedDetails();    
	        g.getUserManagers();
	        g.pdi.Effective_Start_Date__c = Date.today();
	        g.startDistribution();
	
	        g.getDetails();
	        g.getDetails2();
	        g.cleanXSS('val');
	        g.navigateToGetDetails();
	
	        Test.stopTest();
    	}
    	catch(exception e){}
    }

    static testMethod void dacuTestCase() 
    {
        DataAccessControlUtil dacu = new DataAccessControlUtil();
        SObject sObj = new CallidusDataSOurce__c();
        Map<String, Schema.Sobjectfield> fieldsMap = dacu.getFieldMap(sObj);
        String[] expectedFieldMap = new String[]{'Id','Name'};
        Set<String> allowedFields = dacu.getAccessibleFields(sObj, fieldsMap, expectedFieldMap);
        Set<String> filteredList = dacu.getFilteredCreateableFields(fieldsMap, allowedFields);
        filteredList = dacu.getFilteredUpdateableFields(fieldsMap, allowedFields);
        system.assertEquals('success', dacu.isCreateableObjectByUser(sObj));
        system.assertEquals('success', dacu.isUpdateableObjectByUser(sObj));
        system.assertEquals('success', dacu.isDeleteableObjectByUser(sObj));
        dacu.pageMessage(sobj, 'create');
    }
 
}